
module.exports = {
    getImageSize:function(src){
        return new Promise((resolve, reject) => {
            wx.getImageInfo({
                src: src,
                success: (res) => {
                    // console.log( res )
                    let w = res.width;
                    let h = res.height;
                    let maxWidth = 1100;
                    let maxHeight = 1100;

                    // 修改canvas宽高比例
                    if(res.width >= res.height){
                        if (res.width > maxWidth) {
                            w = maxWidth;
                        }
                        h = Math.round(maxWidth * res.height / res.width) * 1;
                    }
                    else{
                        if (res.height > maxHeight) {
                            h = maxHeight;
                        }
                        w = Math.round(maxHeight * res.width / res.height) * 1;
                    };

                    res.cWidth = w;
                    res.cHeight = h;
                    // 修改canvas宽高比例；
                    resolve(res);
                }
            })
        });
    },
    imageToCanvas:function(canvasId,photo){

        return new Promise((resolve, reject) => {
            
            let ctx = wx.createCanvasContext(canvasId);

            // console.log( ctx )
            //ctx.clearRect(0, 0, w, h);
            // console.log(photo.cWidth + "|" + photo.cHeight);
            ctx.drawImage(photo.path, 0, 0, photo.cWidth, photo.cHeight);
            ctx.draw(false,
                setTimeout(() => {
                    wx.canvasToTempFilePath({//把当前画布指定区域的内容导出生成指定大小图片，并返回文件路径
                        canvasId: canvasId,
                        x: 0,
                        y: 0,
                        width: photo.cWidth,
                        height: photo.cHeight,
                        destWidth: photo.cWidth,
                        destHeight: photo.cHeight,
                        fileType: "jpg",
                        quality: 0.9,//图片质量，取值范围在（0，1】
                        success:(res) => {
                            console.log(res.tempFilePath)//给后台传输这个地址
                            let json = {
                                path:res.tempFilePath
                            }
                            wx.getFileInfo({
                                filePath: res.tempFilePath,
                                success: (result) => {
                                    console.log(Math.round(result.size / 1024) + "kb");
                                    json.size = result.size;
                                    resolve(json);
                                },
                                fail: () => { },
                                complete: () => { }
                            });
                        }
                    })
                }, 1000)
            );
        });

    }
}